package com.lgx.mall.business.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lgx.common.entity.Dictionary;
import com.lgx.common.exception.DataException;
import com.lgx.common.web.Constants;
import com.lgx.common.web.Pagination;
import com.lgx.common.web.json.Json2Utils;
import com.lgx.common.web.util.DictUtils;
import com.lgx.common.web.util.EscapeUtils;
import com.lgx.mall.business.entity.RechargeInfo;
import com.lgx.mall.business.service.IRechargeInfoService;
import com.lgx.right.entity.Organization;
import com.lgx.right.entity.User;
import com.lgx.right.service.IOrganizationService;

@Controller
@RequestMapping("/rechargeInfo")
public class RechargeInfoController {

	@Autowired
	private IRechargeInfoService rechargeInfoService;

	public IRechargeInfoService getRechargeInfoService() {
		return rechargeInfoService;
	}

	public void setRechargeInfoService(IRechargeInfoService rechargeInfoService) {
		this.rechargeInfoService = rechargeInfoService;
	}
	
	@Autowired
	private IOrganizationService organizationService;
	
	public IOrganizationService getOrganizationService() {
		return organizationService;
	}

	public void setOrganizationService(IOrganizationService organizationService) {
		this.organizationService = organizationService;
	}

	@RequestMapping("/rechargeInfoMgr.do")
	public String rechargeInfoMgr(HttpServletRequest request,HttpServletResponse response)
	{
		String isConfirmation = request.getParameter("isConfirmation");
		if(!StringUtils.isEmpty(isConfirmation) && isConfirmation.equals("confirmation")){
			//充值状态
			List<Dictionary> rechargeInfoStatus = DictUtils.getDictListByKind(DictUtils.RECHARGEINFO_STATUS);
			request.setAttribute("rechargeInfoStatus", rechargeInfoStatus);
			
			return "mall/business/rechargeInfo/rechargeInfoConfirmationMgr";
		}
		return "mall/business/rechargeInfo/rechargeInfoMgr";
	}
	
	@RequestMapping("/list.do")
	public void list(HttpServletRequest request,HttpServletResponse response)
	{
		String pageNum = request.getParameter("page");
		String pageSize= request.getParameter("rows");
		String isConfirmation = request.getParameter("isConfirmation");
		
		if(StringUtils.isEmpty(pageSize))pageSize = Constants.PAGE_SIZE;
		if(StringUtils.isEmpty(pageNum))pageNum = Constants.FIRST_PAGE_NUM;
		
		Object[] params = new Object[10];
		
		String rechargeDateStart = request.getParameter("rechargeDateStart");
		String rechargeDateEnd = request.getParameter("rechargeDateEnd");
		String fixDateStart = request.getParameter("fixDateStart");
		String fixDateEnd = request.getParameter("fixDateEnd");
		String rechargeInfoStatus = request.getParameter("rechargeInfoStatus");
		
		if(!StringUtils.isEmpty(rechargeDateStart)){
			params[0] = rechargeDateStart+" 00:00:00";
		}
		if(!StringUtils.isEmpty(rechargeDateEnd)){
			params[1] = rechargeDateEnd+" 23:59:59";
		}
		if(!StringUtils.isEmpty(fixDateStart)){
			params[2] = fixDateStart+" 00:00:00";
		}
		if(!StringUtils.isEmpty(fixDateEnd)){
			params[3] = fixDateEnd+" 23:59:59";
		}
		
		if(!StringUtils.isEmpty(isConfirmation) && isConfirmation.equals("confirmation")){
			if(!StringUtils.isEmpty(rechargeInfoStatus)){
				params[4] = rechargeInfoStatus;
			}
		}
		
		Pagination page = this.rechargeInfoService.findRechargeInfoPagination(params, Integer.parseInt(pageSize), Integer.parseInt(pageNum));
		Json2Utils.parseJSON(page, response);
	}
	
	@RequestMapping("/init.do")
	public String init(HttpServletRequest request,HttpServletResponse response)
	{
		String type = request.getParameter("type");
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);//得到当前登录人信息
		
		//商家充值类型
		List<Dictionary> rechargeInfoType = DictUtils.getDictListByKind(DictUtils.RECHARGEINFO_TYPE);
		request.setAttribute("rechargeInfoType", rechargeInfoType);
		
		//商家充值状态
		List<Dictionary> status = DictUtils.getDictListByKind(DictUtils.RECHARGEINFO_STATUS);
		request.setAttribute("status", status);
				
		request.setAttribute("type", type);
		request.setAttribute("orgId", onlineUser.getOrgId());
//		request.setAttribute("orgName", onlineUser.getOrgName());
		request.setAttribute("orgType", onlineUser.getOrgType());
		
		Organization org = this.organizationService.findOrganizationById(onlineUser.getOrgId());
		request.setAttribute("organization", org);
		request.setAttribute("orgName", org.getName());
		request.setAttribute("truename", org.getLegal().getTruename());
		request.setAttribute("sscore", org.getSscore());
		
		return "mall/business/rechargeInfo/rechargeInfo-init";
	}
	
	@RequestMapping("/save.do")
	@ResponseBody
	public String save(HttpServletRequest request,HttpServletResponse response)
	{
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);//得到当前登录人信息
		Organization organization = this.organizationService.findOrganizationByUserId(onlineUser.getId());
		
		String amount = request.getParameter("amount");
		if(!StringUtils.isEmpty(amount))amount = EscapeUtils.unescape(amount);
		String score = request.getParameter("score");
		if(!StringUtils.isEmpty(score))score = EscapeUtils.unescape(score);
		String isRebate = request.getParameter("isRebate");
		if(!StringUtils.isEmpty(isRebate))isRebate = EscapeUtils.unescape(isRebate);
		String type = request.getParameter("type");
		if(!StringUtils.isEmpty(type))type = EscapeUtils.unescape(type);
		
		RechargeInfo r = new RechargeInfo();
		r.setOrgId(organization.getId());
		r.setOrgName(organization.getName());
		r.setOrgType(organization.getType());
		r.setUserId(onlineUser.getId());
		r.setUserName(onlineUser.getUsername());
		r.setUserType(onlineUser.getUserType()+"");
		r.setRechargeDate(new Date());
		r.setUserType(onlineUser.getUserType()+"");
		r.setAmount(Double.parseDouble(amount));
		r.setScore(Double.parseDouble(score));
		r.setStatus(1);
		r.setIsRebate(isRebate);
		if(type.equals("manualRecharge")){
			r.setType("1");
		}else if(type.equals("alipayRecharge")){
			r.setType("2");
		}else if(type.equals("onlineBankRecharge")){
			r.setType("3");
		}
		r.setFixerId(0);
		
		try {
			this.rechargeInfoService.createRechargeInfo(r);
		} catch (DataException e1) {
			e1.printStackTrace();
		}
		
		request.setAttribute("message", "操作成功！");
		return "1";
	}
	
	@RequestMapping("/update.do")
	@ResponseBody
	public String update(HttpServletRequest request,HttpServletResponse response)
	{
		String id = request.getParameter("id");   //接受操作id
		if(!StringUtils.isEmpty(id))id = EscapeUtils.unescape(id);
		String updateType = request.getParameter("updateType");   //接受操作type   2确认，3否认
		RechargeInfo r = this.rechargeInfoService.findRechargeInfoById(Long.parseLong(id));
		
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);//得到当前登录人信息
		Organization org = this.organizationService.findOrganizationById(onlineUser.getOrgId());//根据当前登录人获取对应商家信息
		
		if(updateType.equals("2")){
			r.setFixerId(onlineUser.getId());    //把审批人的id存放到对象中
			r.setFixDate(new Date());            //确定日期
			r.setFixerName(onlineUser.getUsername());    //确定人姓名
			
			//给商家充值
			org.setSscore(r.getAmount());//增加商家的剩余积分
			
			//商家充值给推广中心和运营中心返利
			Double percentPromotioncenter = r.getAmount()*Constants.BRREBATE_PROMOTIONCENTER_TYPE;//计算返利金额
			org.getParent().setSscore(org.getParent().getSscore() + percentPromotioncenter);//增加推广中心的剩余积分
			org.getParent().setAscore(org.getParent().getAscore() + percentPromotioncenter);//增加推广中心的返利钱包
			//预留从公司账户扣除返利的金额
			
			Double percentOperationcenter = r.getAmount()*Constants.BRREBATE_OPERATIONCENTER_TYPE;//计算返利金额
			org.getParent().getParent().setSscore(org.getParent().getParent().getSscore() + percentOperationcenter);//增加运营中心的剩余积分
			org.getParent().getParent().setAscore(org.getParent().getParent().getAscore() + percentOperationcenter);//增加运营中心的返利钱包
			//预留从公司账户扣除返利的金额
		}
		
		r.setStatus(Integer.parseInt(updateType));   //传入审核状态
		
		try {
			this.rechargeInfoService.updateRechargeInfo(r);
			this.organizationService.updateOrganization(org);
		} catch (DataException e1) {
			e1.printStackTrace();
		}
		
		request.setAttribute("message", "操作成功！");
		return "1";
	}

	@RequestMapping("/delete.do")
	@ResponseBody
	public String delete(HttpServletRequest request,HttpServletResponse response)
	{
		String ids = request.getParameter("ids");
		try {
			this.rechargeInfoService.deleteRechargeInfos(ids.split(","));
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}
}
